package cn.tianyigps.obd;

import cn.tianyigps.obd.channels.TYNioServerSocketChannel;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;

/**
 * Created with IDEA
 *
 * @description: TCP入口
 * @author: cui.guibin
 * @create: 2019/3/8 10:36
 * TCP 启动监听端口类
 **/
public class TCP {

    private static final EventLoopGroup BOSS_GROUP = new NioEventLoopGroup();
    private static final EventLoopGroup WORK_GROUP = new NioEventLoopGroup();

    public static void startTCP(int port) {
        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(BOSS_GROUP, WORK_GROUP);
            bootstrap.channel(TYNioServerSocketChannel.class);
            bootstrap.childHandler(new TcpServerChannelInitalizer());
            System.out.println("TCP 服务端开启等待客户端连接....");
            Channel CH = bootstrap.bind(port).sync().channel();
            CH.closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            // 优雅的退出程序
            if (WORK_GROUP != null) {
                WORK_GROUP.shutdownGracefully();
            }
            if (BOSS_GROUP != null) {
                BOSS_GROUP.shutdownGracefully();
            }
            System.out.println("Server is shut down");
        }
    }
}
